<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class StoreGroupStore extends Model
{
    use SoftDeletes;

    protected $table = 'ims_yz_store_group_stores';

    protected $fillable = [
        'group_id',
        'store_id',
        'created_at',
        'updated_at',
        'deleted_at',
    ];

    protected $casts = [
        'id' => 'integer',
        'group_id' => 'integer',
        'store_id' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

    /**
     * 软删除字段名
     */
    const DELETED_AT = 'deleted_at';

    /**
     * 关联门店群组
     */
    public function storeGroup()
    {
        return $this->belongsTo(StoreGroup::class, 'group_id', 'id');
    }

    /**
     * 关联门店
     */
    public function store()
    {
        return $this->belongsTo(Store::class, 'store_id', 'id');
    }

    /**
     * 根据群组ID查询关联门店
     */
    public function scopeByGroup($query, $groupId)
    {
        return $query->where('group_id', $groupId);
    }

    /**
     * 根据门店ID查询关联群组
     */
    public function scopeByStore($query, $storeId)
    {
        return $query->where('store_id', $storeId);
    }

    /**
     * 根据群组ID数组查询关联门店
     */
    public function scopeByGroups($query, array $groupIds)
    {
        return $query->whereIn('group_id', $groupIds);
    }

    /**
     * 获取门店ID列表
     */
    public static function getStoreIdsByGroupIds(array $groupIds)
    {
        return self::whereIn('group_id', $groupIds)
                   ->pluck('store_id')
                   ->unique()
                   ->toArray();
    }

    /**
     * 获取群组ID列表
     */
    public static function getGroupIdsByStoreId($storeId)
    {
        return self::where('store_id', $storeId)
                   ->pluck('group_id')
                   ->toArray();
    }

    /**
     * 批量添加门店到群组
     */
    public static function addStoresToGroup($groupId, array $storeIds)
    {
        $data = [];
        $now = now();
        
        foreach ($storeIds as $storeId) {
            $data[] = [
                'group_id' => $groupId,
                'store_id' => $storeId,
                'created_at' => $now,
                'updated_at' => $now,
            ];
        }
        
        return self::insert($data);
    }

    /**
     * 从群组中移除门店
     */
    public static function removeStoresFromGroup($groupId, array $storeIds = null)
    {
        $query = self::where('group_id', $groupId);
        
        if ($storeIds !== null) {
            $query->whereIn('store_id', $storeIds);
        }
        
        return $query->delete();
    }
}
